// pages/user/user.js
Page({
  data: {
    globalData: getApp().globalData,
    user: {},
    headerImg: '',
    name: '',
    phone: '',
    password: '',
    sex: ''
  },

  onLoad(options) {
    this.getUser(wx.getStorageSync('user').userId)
  },

  getUser(id) {
    let that = this
    wx.request({
      url: this.data.globalData.server + '/user/' + id,
      method: 'GET',
      success(res) {
        let user = res.data.data
        wx.setStorageSync('user', user)
        that.setData({
          user: user,
          headerImg: user.headerImg,
          name: user.username,
          phone: user.phone,
          password: user.password,
          sex: user.sex
        })
      }
    })
  },
  save() {
    let that = this
    wx.request({
      url: this.data.globalData.server + '/user',
      method: 'PUT',
      data: {
        userId: that.data.user.userId,
        headerImg: that.data.headerImg,
        username: that.data.name,
        phone: that.data.phone,
        password: that.data.password,
        sex: that.data.sex
      },
      success(res) {
        that.getUser(wx.getStorageSync('user').userId)
        wx.redirectTo({url: '/pages/my/my'})
      }
    })
  },
  logout() {
    wx.removeStorageSync('user')
    wx.redirectTo({url: '/pages/my/my'})
  }
})
